package com.yunhe.sms.controller;

import com.yunhe.commens.dto.Pagedao;
import com.yunhe.sms.dto.TreeNode;
import com.yunhe.sms.entity.system.Role;
import com.yunhe.sms.service.system.PremissionService;
import com.yunhe.sms.service.system.RoleService;
import com.yunhe.sms.service.system.impl.PremissionServiceImpl;
import com.yunhe.sms.service.system.impl.RoleServiceImpl;
import com.yunhe.webmvc.annocation.RequestBean;
import com.yunhe.webmvc.annocation.RequestMapping;
import com.yunhe.webmvc.annocation.ResponseJSON;
import com.yunhe.webmvc.mode.JsonResponce;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author LeiPeifeng
 * @version V1.0
 * @date 2017/10/24 0024 10:48
 * @Description: 角色业务类
 */
@RequestMapping("/role")
public class RoleController {
    private RoleService roleService= new RoleServiceImpl ();
    private PremissionService premissionService =new PremissionServiceImpl ();

    @RequestMapping("/list")
    public String list(){
        return "system/role/list";
    }

    @RequestMapping("/add")
    public String add(){
        return "system/role/add";
    }

    @RequestMapping("/edit")
    public String edit(HttpServletRequest req, Long id){
        Role role1 = roleService.find ( id );
        req.setAttribute ( "role",role1 );
        return "system/role/edit";
    }

    @RequestMapping("/deleted")
    @ResponseJSON
    public JsonResponce deleted(String ids) {
        roleService.deleted ( ids );
        return new JsonResponce();
    }

    @RequestMapping("/update")
    public String update(@RequestBean Role role,String premssionIds ){
        roleService.update ( role,premssionIds);
        return "redirect:/role/list";
    }

    /**
     *保存角色的同时，把角色和权限的关系也保存在sys_role_premi表中
     * @param role
     * @param premssionIds 在添加页面中设立隐藏域，通过zTree中的方法获取被选中的权限的id,以JSON的格式通过val()放入input中，从而异步获取premssionIds
      * @return
     */
    @RequestMapping("/save")
    public String save(@RequestBean Role role,String premssionIds){
        roleService.save ( role,premssionIds );
        return "redirect:/role/list";
    }

    @RequestMapping("/page")
    @ResponseJSON
    public Pagedao<Role> page(int offset,int limit,HttpServletResponse resp){
        resp.setCharacterEncoding ( "utf-8" );
        Pagedao<Role> page = roleService.page ( offset, limit );
        return page;
    }

    /**
     * 从数据库中查找所有的权限，以JSON的形式返回给ajax中
     * 编辑时，通过页面获取角色的id，通过ajax传给参数
     * @param resp
     * @return
     */
    @RequestMapping("/tree")
    @ResponseJSON
    public JsonResponce tree(HttpServletResponse resp,Long RolId){
        resp.setCharacterEncoding ( "utf-8" );
        List<TreeNode> treeNodes = premissionService.findTreeNodes (RolId);
        return new JsonResponce ( 1,"加载成功",treeNodes );
    }
}
